package login

import (
	"context"
	"net/url"

	"github.com/smartwalle/alipay/v3"

	"2106A-zg6/baidu/gateway/internal/svc"
	"2106A-zg6/baidu/gateway/internal/types"
	"2106A-zg6/baidu/srv/baiduclient"
	"2106A-zg6/baidu/srv/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type NotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NotifyLogic {
	return &NotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *NotifyLogic) Notify(req *types.NotifyRequest, data url.Values) (resp *types.Response, err error) {
	utils.AliPayInit()
	notify, err := utils.CheckNotify(data)
	if err != nil {
		return nil, err
	}

	if notify.TradeStatus != alipay.TradeStatusSuccess {
		return &types.Response{
			Msg:  "订单支付失败",
			Code: 0,
			Data: nil,
		}, nil
	}

	_, err = l.svcCtx.BaiduSrv.OrderStatus(l.ctx, &baiduclient.OrderStatusRequest{
		OrderNo: notify.OutTradeNo,
	})
	if err != nil {
		return nil, err
	}

	return
}
